/**
 * 
 */
package com.caizi.socket.mail;

import java.io.File;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.MimeUtility;

/**
 * @author CAIZI
 * 
 */
public class P2PEmail {

    private boolean debug = false;

    // 定义发件人、收件人、SMTP服务器、用户名、密码、主题、内容等
    private String displayName;
    private String to;
    private String from;
    private String cc;
    private String smtpServer;
    private String username;
    private String password;
    private String subject;
    private String content;
    private boolean ifAuth; // 服务器是否要身份认证
    private Vector<File> file = new Vector<File>(); // 用于保存发送附件的文件名的集合

    public P2PEmail(String displayName, String from, String smtpServer, String username, String password, boolean ifAuth) {
        super();
        this.displayName = displayName;
        this.from = from;
        this.smtpServer = smtpServer;
        this.username = username;
        this.password = password;
        this.ifAuth = ifAuth;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getDisplayName() {
        return displayName;
    }

    public String getTo() {
        return to;
    }

    public void setTo(String to) {
        this.to = to;
    }

    public String getCc() {
        return cc;
    }

    public void setCc(String cc) {
        this.cc = cc;
    }

    public String getFrom() {
        return from;
    }

    public String getSmtpServer() {
        return smtpServer;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getSubject() {
        return subject;
    }

    public String getContent() {
        return content;
    }

    public boolean isIfAuth() {
        return ifAuth;
    }

    public Vector<File> getFile() {
        return file;
    }

    public void setFile(Vector<File> file) {
        this.file = file;
    }

    public void setDeug(boolean debug) {
        this.debug = debug;
    }

    /**
     * 发送邮件
     */
    public void send() {
        Session session = null;
        Properties props = System.getProperties();
        props.put("mail.smtp.host", smtpServer);
        if (ifAuth) { // 服务器需要身份认证
            props.put("mail.smtp.auth", "true");
            SmtpAuth smtpAuth = new SmtpAuth(username, password);
            session = Session.getDefaultInstance(props, smtpAuth);
        } else {
            props.put("mail.smtp.auth", "false");
            session = Session.getDefaultInstance(props, null);
        }
        session.setDebug(debug);
        Transport trans = null;
        try {
            Message msg = new MimeMessage(session);
            try {
                Address from_address = new InternetAddress(from, displayName);
                msg.setFrom(from_address);
            } catch (java.io.UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            InternetAddress[] address = { new InternetAddress(to) };
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject(subject);
            msg.addRecipient(RecipientType.CC, new InternetAddress(cc));
            Multipart mp = new MimeMultipart();
            MimeBodyPart mbp = new MimeBodyPart();
            mbp.setContent(content.toString(), "text/html;charset=gb2312");
            mp.addBodyPart(mbp);
            if (null != file && !file.isEmpty()) {// 有附件
                Enumeration<File> efile = file.elements();
                while (efile.hasMoreElements()) {
                    mbp = new MimeBodyPart();
                    String filename = efile.nextElement().toString(); // 选择出每一个附件名
                    FileDataSource fds = new FileDataSource(filename); // 得到数据源
                    mbp.setDataHandler(new DataHandler(fds)); // 得到附件本身并至入BodyPart
                    mbp.setFileName(MimeUtility.encodeText(fds.getName())); // 得到文件名同样至入BodyPart
                    mp.addBodyPart(mbp);
                }
                file.removeAllElements();
            }
            msg.setContent(mp); // Multipart加入到信件
            msg.setSentDate(new Date()); // 设置信件头的发送日期
            // 发送信件
            msg.saveChanges();
            trans = session.getTransport("smtp");
            trans.connect(smtpServer, username, password);
            trans.sendMessage(msg, msg.getAllRecipients());
            trans.close();
            System.out.println("邮件发送" + to + "成功");
        } catch (Exception e) {
            System.out.println("邮件发送" + to + "失败！错误原因：" + e.getMessage());
        }
    }

    class SmtpAuth extends javax.mail.Authenticator {
        private String username, password;

        public SmtpAuth(String username, String password) {
            this.username = username;
            this.password = password;
        }

        protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
            return new javax.mail.PasswordAuthentication(username, password);
        }
    }
}
